<template>
  <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"
        @row-save="handleSave"
        @row-del="handleDel"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @refresh-change="handleRefreshChange"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            @click="handleRowDel"
            :loading="bachDeleting"
            v-perm="'/admin/user/batch-remove'"
            icon="el-icon-remove"
            size="small"
          >批量删除</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            @click.stop="handleResetPwd(scope.row)"
            icon="el-icon-edit"
            v-perm="'/admin/user/restpwd'"
            size="mini"
          >重置密码</el-button>
          <el-button
            type="text"
            v-if="scope.row.Status == 1"
            @click.stop="handleStopUser(scope.row)"
            v-perm="'/admin/user/stop'"
            icon="el-icon-edit"
            size="mini"
          >停用</el-button>
          <el-button
            type="text"
            v-perm="'/admin/user/start'"
            v-if="scope.row.Status == 0"
            @click.stop="handleStartUser(scope.row)"
            icon="el-icon-edit"
            size="mini"
          >启用</el-button>
        </template>
        <template slot="menuLeft">
          <el-button
            type="primary"
            v-perm="'/admin/user/export'"
            @click="handleExport"
            :loading="downloadLoading"
            icon="el-icon-download"
            size="small"
          >导出</el-button>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>
  <script>
import { validatenull } from "@/util/validate";
import * as apiObj from "@/api/admin";
import { adminTableOption } from "@/const/admin/adminTableOption.js";

export default {
  data() {
    return {
      bachDeleting: false,
      tableOption: {}, //表格设置属性
      tableData: [], //表格的数据
      tablePage: 1,
      tableLoading: false,
      downloadLoading: false,
      tableQueryParam: {},
      page: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10 //每页显示多少条
      }
    };
  },
  created() {
    //初始化数据格式
    this.tableOption = adminTableOption;
    this.handleList();
  },
  methods: {
    handleRowDel() {
      if (validatenull(this.currentSelectedRowIds)) {
        this.$notify({
          showClose: true,
          message: "请至少选择一行要删除的数据",
          type: "error"
        });
        return false;
      }
      this.$confirm("是否确认删除所选择记录吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.bachDeleting = true;
        apiObj
          .remove(this.currentSelectedRowIds)
          .then(() => {
            this.bachDeleting = false;
            this.handleList();
            this.$message({
              showClose: true,
              message: "成功",
              type: "success"
            });
          })
          .catch(() => {
            this.bachDeleting = false;
          });
      });
    },
    handleResetPwd(row) {
      this.showConfirm("确认重置密码吗?", () => {
        apiObj.resetPwd(row.Id).then(data => {
          this.alert("重置密码成功，请使用新密码:" + data);
        });
      });
    },

    handleSelectionChange(args) {
      this.currentSelectedRowIds = args.map(el => el.Id);
    },
    handleSearchChange(params) {
      this.tableQueryParam = params;
      this.handleList();
    },
    handleStopUser(row) {
      this.showConfirm("确定停用该账户吗", () => {
        apiObj.setOffline(row.Id).then(() => {
          row.Status = 0;
          this.showSuccess();
        });
      });
    },
    handleStartUser(row) {
      this.showConfirm("确定启用该账户吗", () => {
        apiObj.setOnline(row.Id).then(() => {
          row.Status = 1;
          this.showSuccess();
        });
      });
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate(row, index, done, reject) {
      apiObj
        .update(row)
        .then(() => {
          this.handleList();
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success"
          });
          done();
        })
        .catch(() => {
          reject();
        });
    },

    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave(row, done, reject) {
      apiObj
        .create(row)
        .then(pwd => {
          this.handleList();
          this.alert("新建账号成功，密码是：" + pwd);
          done();
        })
        .catch(() => {
          reject();
        });
    },
    handleCurrentChange(page) {
      this.page.currentPage = page;
      this.handleList();
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.handleList();
    },
    handleRefreshChange() {
      this.handleList();
    },
    /**
     * @title 获取数据
     * @detail 赋值为tableData表格即可
     *
     **/
    handleList() {
      this.tableLoading = true;
      apiObj
        .list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
        .then(data => {
          this.tableData = data.rows;
          this.page.total = data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    handleExport() {
      this.downloadLoading = true;
      apiObj
        .list({
          pageNo: 1,
          pageSize: 10000,
          ...this.tableQueryParam
        })
        .then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const tHeader = [
              "账号",
              "姓名",
              "角色",
              "状态",
              "最后登录IP",
              "创建时间",
              "修改时间",
              "地区",
              "银行名称",
              "开户账号",
              "开户支行",
              "手机号",
              "刷手数量",
              "备注"
            ];
            const filterVal = [
              "Username",
              "Realname",
              "RoleId",
              "Status",
              "LastLoginIp",
              "CreateTime",
              "ModifyTime",
              "Area",
              "BankName",
              "BankAccount",
              "BankBranch",
              "Telephone",
              "ScalperNum",
              "Note"
            ];
            const data = this.formatJson(filterVal, res.rows);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "用户列表"
            });
            this.downloadLoading = false;
          });
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          return v[j];
        })
      );
    },
    handleDel(row, index) {
      this.$confirm("是否确认删除序号为" + (index + 1), "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          apiObj.remove([row.Id]).then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "删除成功",
              type: "success"
            });
          });
        })
        .catch(() => {});
    }
  }
};
</script>
